<template>
<page-container title="数据源管理">
  <div class="data-source-list">
  <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd()">新增数据源</el-button>
      <el-input
      v-model="searchId"
      placeholder="请输入数据源ID"
      clearable
      @clear="handleSearch"
      style="width: 250px; margin-left: 10px"
      @keyup.native.enter="handleSearch"
      >
      <template #append>
        <el-button icon="el-icon-search" @click="handleSearch"></el-button>
      </template>
      </el-input>
    </div>
    <!-- 数据源表格 -->
    <el-table
      :data="dataSourceList"
      style="width: 100%;"
      :fit="true"
      :border="true"
      header-height="50"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="数据源名称" min-width="120"></el-table-column>
      <el-table-column prop="type" label="数据源类型" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="
            scope.row.type === 'MYSQL' ? 'primary' :
            scope.row.type === 'POSTGRES' ? 'success' :
            scope.row.type === 'ORACLE' ? 'warning' :
            scope.row.type === 'SQLSERVER' ? 'danger' : 'info'
          ">
            {{ scope.row.type === 'MYSQL' ? 'MySQL' :
               scope.row.type === 'POSTGRES' ? 'PostgreSQL' :
               scope.row.type === 'ORACLE' ? 'Oracle' :
               scope.row.type === 'SQLSERVER' ? 'SQL Server' :
               scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="host" label="主机地址" min-width="160"></el-table-column>
      <el-table-column prop="port" label="端口" width="80" />
      <el-table-column prop="databaseName" label="数据库名" min-width="120" />
      <el-table-column prop="username" label="用户名" min-width="120" />
      <el-table-column prop="status" label="状态" min-width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
          <el-tag size="mini" :type="scope.row.status === 1 ? 'success' : 'info'" style="margin-left: 5px;">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" align="center">
        <template #default="{row}">
          <el-button size="mini" type="success" @click="handleTest(row)">测试连接</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 新增数据源弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="dataSourceForm" label-width="120px">
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据源名称（最多100个字符）" />
        </el-form-item>
        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择数据源类型（如MySQL/PostgreSQL）" style="width: 100%;">
            <el-option label="MySQL" value="MYSQL"></el-option>
            <el-option label="PostgreSQL" value="POSTGRES"></el-option>
            <el-option label="Oracle" value="ORACLE"></el-option>
            <el-option label="SQL Server" value="SQLSERVER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主机地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入主机地址（IP或域名）" />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口号（如MySQL默认3306）" />
        </el-form-item>
        <el-form-item label="数据库名" prop="database">
          <el-input v-model="form.database" placeholder="请输入数据库名（最多100个字符）" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码（建议加密）" show-password />
        </el-form-item>
        <el-form-item label="额外参数" prop="params">
          <el-input v-model="form.params" placeholder="请输入连接的额外参数，如：useSSL=false&serverTimezone=UTC（JSON格式）" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
          v-model="form.status"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注（可选）" />
        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>

  </div>
</page-container>

</template>
<script>
import PageContainer from '@/components/PageContainer.vue'
// import EditDialog from './EditDialog.vue'
import {
  getDataSourceList,
  testDataSource,
  deleteDataSource,
  enableDataSource,
  disableDataSource,
  updateDataSource,
  addDataSource,
  getDataSourceById
} from '@/api/source'
export default {
  name: 'DataSourceList',
  components: {
    PageContainer
  },
  data () {
    return {
      // 数据源列表数据
      dataSourceList: [],
      loading: false, // 加载状态
      dataSourceName: '', // 数据源名称
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页大小
      total: 0, // 总条数
      searchId: '', // 搜索ID
      dialogVisible: false, // 弹窗状态
      dialogTitle: '添加数据源', // 弹窗标题
      submitLoading: false, // 提交状态
      form: { // 表单数据
        id: null,
        name: '',
        type: 'MYSQL',
        host: '',
        port: '',
        database: '',
        username: '',
        password: '',
        params: '',
        remark: '',
        status: 1
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入数据源名称', trigger: 'blur' },
          { max: 100, message: '数据源名称长度不能超过100个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择数据源类型', trigger: 'change' },
          { max: 50, message: '数据源类型长度不能超过50个字符', trigger: 'blur' }
        ],
        host: [
          { required: true, message: '请输入主机地址', trigger: 'blur' },
          { max: 255, message: '主机地址长度不能超过255个字符', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' },
          { pattern: /^\d+$/, message: '端口号必须是数字', trigger: 'blur' }
        ],
        database: [
          { required: true, message: '请输入数据库名', trigger: 'blur' },
          { max: 100, message: '数据库名长度不能超过100个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 100, message: '用户名长度不能超过100个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 255, message: '密码长度不能超过255个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 构建完整的URL
    buildUrl () {
      return function (item) {
        const { type, host, port, database, params } = item
        let url = ''

        if (type === 'MYSQL') {
          url = `jdbc:mysql://${host}:${port}/${database}`
          if (params) {
            url += `?${params}`
          }
        } else if (type === 'POSTGRES') {
          url = `jdbc:postgresql://${host}:${port}/${database}`
          if (params) {
            url += `?${params}`
          }
        } else if (type === 'ORACLE') {
          url = `jdbc:oracle:thin:@${host}:${port}:${database}`
        } else if (type === 'SQLSERVER') {
          url = `jdbc:sqlserver://${host}:${port};database=${database}`
          if (params) {
            url += `;${params}`
          }
        }

        return url
      }
    }
  },
  created () {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData () {
      this.loading = true
      try {
        const res = await getDataSourceList({
          current: this.currentPage,
          size: this.pageSize,
          name: this.searchName
        })
        console.log(res)
        if (res.code === 200) {
          this.dataSourceList = res.data.records
          this.total = res.data.total
        } else {
          this.$message.error(res.msg || '获取数据源列表失败')
        }
      } catch (error) {
        console.error('获取数据源列表出错', error)
        this.$message.error(error.msg || '获取数据源列表失败')
      } finally {
        this.loading = false
      }
    },

    // 添加数据源
    handleAdd () {
      this.dialogTitle = '添加数据源'
      this.dialogVisible = true
      this.resetForm()
    },

    // 编辑数据源
    handleEdit (row) {
      this.dialogTitle = '编辑数据源'
      this.dialogVisible = true
      // 填充表单数据
      this.$nextTick(() => {
        // 解析URL获取连接信息
        const urlParts = this.parseConnectionUrl(row.url)

        this.form = {
          id: row.id,
          name: row.name,
          type: row.type,
          host: urlParts.host || '',
          port: urlParts.port || '',
          database: urlParts.database || '',
          username: row.username,
          password: row.password || '', // 密码通常不会返回
          params: urlParts.params || '',
          remark: row.remark || '',
          status: row.status
        }
      })
    },

    // 解析连接URL
    parseConnectionUrl (url) {
      const result = {
        host: '',
        port: '',
        database: '',
        params: ''
      }

      if (!url) return result

      try {
        if (url.includes('mysql')) {
          // jdbc:mysql://host:port/database?params
          const basicRegex = /jdbc:mysql:\/\/([^:]+):(\d+)\/([^?]+)/
          const matches = url.match(basicRegex)
          if (matches && matches.length === 4) {
            result.host = matches[1]
            result.port = matches[2]
            result.database = matches[3]
          }

          // 解析参数
          const paramsMatch = url.match(/\?(.+)$/)
          if (paramsMatch && paramsMatch.length === 2) {
            result.params = paramsMatch[1]
          }
        } else if (url.includes('postgresql')) {
          // jdbc:postgresql://host:port/database?params
          const basicRegex = /jdbc:postgresql:\/\/([^:]+):(\d+)\/([^?]+)/
          const matches = url.match(basicRegex)
          if (matches && matches.length === 4) {
            result.host = matches[1]
            result.port = matches[2]
            result.database = matches[3]
          }

          // 解析参数
          const paramsMatch = url.match(/\?(.+)$/)
          if (paramsMatch && paramsMatch.length === 2) {
            result.params = paramsMatch[1]
          }
        } else if (url.includes('oracle')) {
          // jdbc:oracle:thin:@host:port:database
          const regex = /jdbc:oracle:thin:@([^:]+):(\d+):([^?]+)/
          const matches = url.match(regex)
          if (matches && matches.length === 4) {
            result.host = matches[1]
            result.port = matches[2]
            result.database = matches[3]
          }
        } else if (url.includes('sqlserver')) {
          // jdbc:sqlserver://host:port;database=database;params
          const hostPortRegex = /jdbc:sqlserver:\/\/([^:]+):(\d+)/
          const dbRegex = /database=([^;]+)/

          const hostPortMatches = url.match(hostPortRegex)
          const dbMatches = url.match(dbRegex)

          if (hostPortMatches && hostPortMatches.length === 3) {
            result.host = hostPortMatches[1]
            result.port = hostPortMatches[2]
          }

          if (dbMatches && dbMatches.length === 2) {
            result.database = dbMatches[1]
          }

          // 解析其他参数 - 移除host:port和database部分
          if (url.includes(';')) {
            const fullParams = url.split(';').slice(1).join(';')
            if (fullParams) {
              // 移除database=xxx部分
              const paramsParts = fullParams.split(';').filter(part => !part.startsWith('database='))
              result.params = paramsParts.join(';')
            }
          }
        }
      } catch (error) {
        console.error('解析URL出错', error)
      }

      return result
    },
    // 删除数据源
    handleDelete (id) {
      this.$confirm('确定要删除该数据源吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteDataSource(id)
          console.log(res)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除数据源出错', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
      this.loadData()
    },
    // 测试连接
    async handleTest (row) {
      try {
        this.$message.info('正在测试连接...')
        const res = await testDataSource(row.id)
        if (res.code === 200) {
          this.$message.success('连接成功')
        } else {
          this.$message.error(res.msg || '连接失败')
        }
      } catch (error) {
        this.$message.error('连接失败:' + (error.message || '未知错误'))
      }
    },
    // 切换数据源状态
    async handleStatusChange (row) {
      try {
        const newStatus = row.status
        let res

        if (newStatus === 1) {
          res = await enableDataSource(row.id)
        } else {
          res = await disableDataSource(row.id)
        }

        if (res.code === 200) {
          this.$message.success(newStatus === 1 ? '启用成功' : '禁用成功')
        } else {
          // 恢复状态
          row.status = newStatus === 1 ? 0 : 1
          this.$message.error(res.msg || (newStatus === 1 ? '启用失败' : '禁用失败'))
        }
      } catch (error) {
        // 恢复状态
        row.status = row.status === 1 ? 0 : 1
        console.error('切换状态出错', error)
        this.$message.error('操作失败')
      }
    },
    // 重置表单
    resetForm () {
      if (this.$refs.dataSourceForm) {
        this.$refs.dataSourceForm.resetFields()
      }

      this.form = {
        id: null,
        name: '',
        type: 'MYSQL',
        host: '',
        port: '',
        database: '',
        username: '',
        password: '',
        params: '',
        remark: '',
        status: 1
      }
    },
    // 提交表单
    submitForm () {
      this.$refs.dataSourceForm.validate(async valid => {
        if (!valid) return

        try {
          this.submitLoading = true

          // 构建提交数据 - 根据后端实体类字段名匹配
          const dataSourceDTO = {
            id: this.form.id,
            name: this.form.name,
            type: this.form.type,
            url: this.buildUrl(this.form),
            host: this.form.host,
            port: this.form.port,
            databaseName: this.form.database, // 匹配后端实体类字段名
            username: this.form.username,
            password: this.form.password,
            params: this.form.params,
            remark: this.form.remark,
            status: this.form.status
          }

          let res
          if (this.form.id) {
            // 更新
            res = await updateDataSource(dataSourceDTO)
          } else {
            // 新增
            res = await addDataSource(dataSourceDTO)
          }

          if (res.code === 200) {
            this.$message.success(this.form.id ? '修改成功' : '添加成功')
            this.dialogVisible = false
            this.loadData()
          } else {
            this.$message.error(res.msg || (this.form.id ? '修改失败' : '添加失败'))
          }
        } catch (error) {
          console.error(this.form.id ? '修改数据源出错' : '添加数据源出错', error)
          this.$message.error(this.form.id ? '修改失败' : '添加失败')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 分页处理
    handleSizeChange (size) {
      this.pageSize = size
      this.loadData()
    },
    handleCurrentChange (page) {
      this.currentPage = page
      this.loadData()
    },
    // 根据id搜索数据源
    async handleSearch () {
      // 重置到第一页
      this.currentPage = 1

      // 验证输入的id是否为数字
      if (this.searchId && !/^\d+$/.test(this.searchId)) {
        this.$message.warning('请输入正确的数据源ID')
        return
      }

      if (this.searchId) {
        try {
          const res = await getDataSourceById(this.searchId)
          console.log('查询数据源res', res)
          if (res.code === 200 && res.data) {
            this.dataSourceList = [res.data]
            this.total = 1
          } else {
            this.dataSourceList = []
            this.total = 0
            this.$message.warning(res.msg || '未找到该数据源ID的数据')
          }
        } catch (error) {
          console.error('查询数据源出错:', error)
          this.$message.error('查询数据源失败: ' + (error.message || '未知错误'))
          this.dataSourceList = []
          this.total = 0
        }
      } else {
        // 加载数据
        this.loadData()
      }
    }
  }
}
</script>
<style scoped>
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: end;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.el-table th{
  vertical-align: middle;
  line-height: 60px;
}

.data-source-list {
  width: 100%;
  padding: 0;
  margin: 0;
}
.data-source-list >>> .el-table th {
  height: 100px;
  line-height: 100px;
  vertical-align: middle;
  padding: 0;
}
</style>
